#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <assert.h>

pthread_rwlock_t rwlock;

int number = 0;

void* read_func(void *arg) {
    for (int i = 0; i < 50; i++) {
        pthread_rwlock_rdlock(&rwlock);
        printf("read number: %d\n", number);
        pthread_rwlock_unlock(&rwlock);
        usleep(rand() % 5);
    }
    return NULL;
    
}
void* write_func(void *arg) {
    for (int i = 0; i < 50; ++i) {
        pthread_rwlock_wrlock(&rwlock);
        int cur = number;
        ++cur;
        number = cur;
        printf("write number %d\n", number);
        pthread_rwlock_unlock(&rwlock);
        usleep(rand() % 5);
    }
    return NULL;
}

int main() {
    pthread_t r_tid[3], w_tid[3];
    pthread_rwlock_init(&rwlock, NULL);  

    for (int i = 0; i < 3; i++) {
        pthread_create(&r_tid[i], NULL, read_func, NULL);
        pthread_create(&w_tid[i], NULL, write_func, NULL);
    }

    for (int i = 0; i < 3; i++) {
        pthread_join(r_tid[i], NULL);
        pthread_join(w_tid[i], NULL);
    }
    pthread_rwlock_destroy(&rwlock);
    printf("%d\n", number);
}

